package com.ruoyi.monitor.service.impl;

import java.util.*;

import com.ruoyi.base.domain.BusWaterSegment;
import com.ruoyi.base.domain.BussinessItemVo;
import com.ruoyi.base.service.PublicToolsService;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.monitor.domain.BusWaterAutomonitorevaluateHourdata;
import com.ruoyi.system.service.ISysDictDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.monitor.mapper.BusWaterAutomonitorevaluateDaydataMapper;
import com.ruoyi.monitor.domain.BusWaterAutomonitorevaluateDaydata;
import com.ruoyi.monitor.service.IBusWaterAutomonitorevaluateDaydataService;
import org.springframework.util.CollectionUtils;

/**
 * 自动站日监测评价Service业务层处理
 * 
 * @author maliang
 * @date 2025-08-11
 */
@Service
public class BusWaterAutomonitorevaluateDaydataServiceImpl implements IBusWaterAutomonitorevaluateDaydataService 
{
    @Autowired
    private BusWaterAutomonitorevaluateDaydataMapper busWaterAutomonitorevaluateDaydataMapper;
    @Autowired
    private PublicToolsService publicToolsService;
    @Autowired
    private ISysDictDataService sysDictDataService;

    /**
     * 查询自动站日监测评价
     * 
     * @param mn 自动站日监测评价主键
     * @return 自动站日监测评价
     */
    @Override
    public BusWaterAutomonitorevaluateDaydata selectBusWaterAutomonitorevaluateDaydataByMn(String mn)
    {
        return busWaterAutomonitorevaluateDaydataMapper.selectBusWaterAutomonitorevaluateDaydataByMn(mn);
    }

    /**
     * 查询自动站日监测评价列表
     * 
     * @param busWaterAutomonitorevaluateDaydata 自动站日监测评价
     * @return 自动站日监测评价
     */
    @Override
    public List<BusWaterAutomonitorevaluateDaydata> selectBusWaterAutomonitorevaluateDaydataList(BusWaterAutomonitorevaluateDaydata busWaterAutomonitorevaluateDaydata)
    {
        return busWaterAutomonitorevaluateDaydataMapper.selectBusWaterAutomonitorevaluateDaydataList(busWaterAutomonitorevaluateDaydata);
    }

    /**
     * 新增自动站日监测评价
     * 
     * @param busWaterAutomonitorevaluateDaydata 自动站日监测评价
     * @return 结果
     */
    @Override
    public int insertBusWaterAutomonitorevaluateDaydata(BusWaterAutomonitorevaluateDaydata busWaterAutomonitorevaluateDaydata)
    {
        return busWaterAutomonitorevaluateDaydataMapper.insertBusWaterAutomonitorevaluateDaydata(busWaterAutomonitorevaluateDaydata);
    }

    /**
     * 修改自动站日监测评价
     * 
     * @param busWaterAutomonitorevaluateDaydata 自动站日监测评价
     * @return 结果
     */
    @Override
    public int updateBusWaterAutomonitorevaluateDaydata(BusWaterAutomonitorevaluateDaydata busWaterAutomonitorevaluateDaydata)
    {
        return busWaterAutomonitorevaluateDaydataMapper.updateBusWaterAutomonitorevaluateDaydata(busWaterAutomonitorevaluateDaydata);
    }

    /**
     * 批量删除自动站日监测评价
     * 
     * @param mns 需要删除的自动站日监测评价主键
     * @return 结果
     */
    @Override
    public int deleteBusWaterAutomonitorevaluateDaydataByMns(String[] mns)
    {
        return busWaterAutomonitorevaluateDaydataMapper.deleteBusWaterAutomonitorevaluateDaydataByMns(mns);
    }

    /**
     * 删除自动站日监测评价信息
     * 
     * @param mn 自动站日监测评价主键
     * @return 结果
     */
    @Override
    public int deleteBusWaterAutomonitorevaluateDaydataByMn(String mn)
    {
        return busWaterAutomonitorevaluateDaydataMapper.deleteBusWaterAutomonitorevaluateDaydataByMn(mn);
    }

    @Override
    public List<Map> qualityLevelStatis(String id, String startTime, String endTime) {
        List<Map> dataMapList = new ArrayList<>();

        SysDictData dictParam = new SysDictData();
        dictParam.setDictType("water_quality_level");
        List<SysDictData> sysDictDataList = sysDictDataService.selectDictDataList(dictParam);
        Date startDate = DateUtils.dateTime("yyyy-MM-dd HH:mm:ss",startTime+" 00:00:00");
        Date endDate = DateUtils.dateTime("yyyy-MM-dd HH:mm:ss",endTime+" 23:59:59");
        List<Map> mapList = busWaterAutomonitorevaluateDaydataMapper.qualityLevelStatis(id,startDate,endDate);

        for (SysDictData sysDictData : sysDictDataList) {
            Map dataMap = new HashMap<>();
            String value = "0";
            if(!CollectionUtils.isEmpty(mapList)){
                for (Map map : mapList) {
                    String qualityLevelName = StringUtils.getString(map.get("qualityLevelName"));
                    if(qualityLevelName.equals(sysDictData.getDictLabel())){
                        value = StringUtils.getString(map.get("qualityLevelCount"));
                        break;
                    }
                }
            }
            dataMap.put(sysDictData.getDictLabel(),value);
            dataMapList.add(dataMap);
        }

        return dataMapList;
    }

    @Override
    public Map statisItemCount(String id, String startTime, String endTime) {
        Map<String,List<String>> itemDataList = new HashMap();
        BussinessItemVo vo = new BussinessItemVo();
        vo.setBussinessCategoryCode("Auto");
        List<Map<String,Object>> itemList=publicToolsService.bussinessItemData(vo);
        Date startDate = DateUtils.dateTime("yyyy-MM-dd HH:mm:ss",startTime+"-01 00:00:00");
        Date endDate = DateUtils.dateTime("yyyy-MM-dd HH:mm:ss",endTime+"-31 23:59:59");

        List<Map> statisList = busWaterAutomonitorevaluateDaydataMapper.statisItemCount(id,startDate,endDate);

        while(!startDate.after(endDate)){
            String dayTime = DateUtils.parseDateToStr("yyyy-MM",startDate);
            if(itemDataList.containsKey("dateList")){
                List<String> dateList = itemDataList.get("dateList");
                dateList.add(dayTime);
                itemDataList.put("dateList",dateList);
            }else{
                List<String> dateList = new ArrayList<>();
                dateList.add(dayTime);
                itemDataList.put("dateList",dateList);
            }
            for (Map<String, Object> itemMap : itemList) {
                String itemName = StringUtils.getString(itemMap.get("itemName"));
                Map itemDataMap = new HashMap();
                itemDataMap.put("day",dayTime);
                itemDataMap.put("item",itemName);
                int count = 0;
                for (Map statisMap : statisList) {
                    String statisDay = StringUtils.getString(statisMap.get("dataDay"));
                    String statisItem = StringUtils.getString(statisMap.get("itemName"));
                    String dataCount = StringUtils.getString(statisMap.get("dataCount"));
                    if(statisDay.equals(dayTime) && itemName.equals(statisItem)){
                        count = Integer.valueOf(dataCount);
                        break;
                    }
                }
                if(itemDataList.containsKey(itemName)){
                    List<String> dateList = itemDataList.get(itemName);
                    dateList.add(count+"");
                    itemDataList.put(itemName,dateList);
                }else{
                    List<String> dateList = new ArrayList<>();
                    dateList.add(count+"");
                    itemDataList.put(itemName,dateList);
                }
            }
            startDate = DateUtils.addMonths(startDate,1);
        }
        return itemDataList;
    }

    @Override
    public Map statisCalendar(String id, String year) {
        Map statisMap = new LinkedHashMap();
        List<Map> list = new ArrayList<>();
        String currMonth = DateUtils.dateTimeNow("yyyy-MM");
        String currYear = DateUtils.dateTimeNow("yyyy");
        Date startDate = DateUtils.dateTime("yyyy-MM-dd HH:mm:ss",year+"-01-01 00:00:00");
        Date endDate = DateUtils.dateTime("yyyy-MM-dd HH:mm:ss",year+"-12-31 23:59:59");

        BusWaterAutomonitorevaluateDaydata param = new BusWaterAutomonitorevaluateDaydata();
        param.setSegmentid(id);
        param.setStartTime(startDate);
        param.setEndTime(endDate);
        List<BusWaterAutomonitorevaluateDaydata> dataList = selectBusWaterAutomonitorevaluateDaydataList(param);
        Map<String,Map<String,Integer>> monthCountMap = new LinkedHashMap<>();
        Map<String,List<Map>> monthDataListMap = new LinkedHashMap<>();

        int allDays = 0;
        int allDataDays = 0;
        int allOverStandardDays = 0;
        int allNoOverStandardDays = 0;
        while(!startDate.after(endDate)){
            allDays++;
            String day = DateUtils.parseDateToStr("yyyy-MM-dd",startDate);
            String month = DateUtils.parseDateToStr("yyyy-MM",startDate);
            List<Map> dataMapList = new ArrayList<>();
            if(monthDataListMap.containsKey(month)){
                dataMapList = monthDataListMap.get(month);
            }
            int days = 0;
            int dataDays = 0;
            int overStandardDays = 0;
            int noOverStandardDays = 0;
            Map<String,Integer> monthMap = new HashMap<>();
            if(monthCountMap.containsKey(month)){
                monthMap = monthCountMap.get(month);
                days = monthMap.get("days");
                dataDays = monthMap.get("dataDays");
                overStandardDays = monthMap.get("overStandardDays");
                noOverStandardDays = monthMap.get("noOverStandardDays");
            }

            Map dataMap = new HashMap();
            dataMap.put("day",day);
            String isOverStandard = "1";
            String qualitylevelname = "无类别";
            for (BusWaterAutomonitorevaluateDaydata busWaterAutomonitorevaluateDaydata : dataList) {
                String dataDay = DateUtils.parseDateToStr("yyyy-MM-dd",busWaterAutomonitorevaluateDaydata.getSampletime());
                if(dataDay.equals(day)){
                    allDataDays = allDataDays + 1;
                    if(StringUtils.isNotEmpty(busWaterAutomonitorevaluateDaydata.getIsoverstandard())){
                        isOverStandard = busWaterAutomonitorevaluateDaydata.getIsoverstandard();
                    }
                    if(StringUtils.isNotEmpty(busWaterAutomonitorevaluateDaydata.getQualitylevelname())){
                        qualitylevelname = busWaterAutomonitorevaluateDaydata.getQualitylevelname();
                    }
                    dataDays = dataDays + 1;
                    break;
                }
            }
            if("1".equals(isOverStandard)){
                overStandardDays = overStandardDays + 1;
                allOverStandardDays = allOverStandardDays + 1;
            }else{
                noOverStandardDays = noOverStandardDays + 1;
                allNoOverStandardDays = allNoOverStandardDays + 1;
            }
            days = days + 1;

            monthMap.put("days",days);
            monthMap.put("dataDays",dataDays);
            monthMap.put("overStandardDays",overStandardDays);
            monthMap.put("noOverStandardDays",noOverStandardDays);
            monthCountMap.put(month,monthMap);
            dataMap.put("isOverStandard",isOverStandard);
            dataMap.put("qualitylevelname",qualitylevelname);
            dataMapList.add(dataMap);
            monthDataListMap.put(month,dataMapList);
            startDate = DateUtils.addDays(startDate,1);
        }
        for (String key : monthCountMap.keySet()) {
            Map data = new LinkedHashMap();
            data.put("month",key);
            Map<String,Integer> monthCount = monthCountMap.get(key);
            int days = monthCount.get("days");
            int overStandardDays = monthCount.get("overStandardDays");
            int noOverStandardDays = monthCount.get("noOverStandardDays");
            String overStandardPropor = String.format("%.0f",((float)overStandardDays/(float) days)*100f);
            String noOverStandardPropor = String.format("%.0f",((float)noOverStandardDays/(float) days)*100f);
            data.putAll(monthCountMap.get(key));
            data.put("overStandardPropor",overStandardPropor+"%");
            data.put("noOverStandardPropor",noOverStandardPropor+"%");
            data.put("dayList",monthDataListMap.get(key));
            if(StringUtils.compare(key,currMonth)>0){
                data.put("dayList",new ArrayList<>());
                data.put("dataDays",0);
                data.put("overStandardDays",0);
                data.put("overStandardPropor","0%");
            }
            list.add(data);
        }
        String overStandardPropor = String.format("%.0f",((float)allOverStandardDays/(float) allDays)*100f);
        String noOverStandardPropor = String.format("%.0f",((float)allNoOverStandardDays/(float) allDays)*100f);
        statisMap.put("days",allDays);
        statisMap.put("dataDays",allDataDays);
        statisMap.put("overStandardDays",allOverStandardDays);
        statisMap.put("noOverStandardDays",allNoOverStandardDays);
        statisMap.put("overStandardPropor",overStandardPropor+"%");
        statisMap.put("noOverStandardPropor",noOverStandardPropor+"%");
        statisMap.put("monthData",list);
        return statisMap;
    }

    @Override
    public Map trendQuality(String id, String startTime, String endTime) {
        Map<String,List<String>> itemDataList = new HashMap();

        SysDictData sysDictDataParam = new SysDictData();
        sysDictDataParam.setDictType("water_quality_level");
        List<SysDictData> sysDictDataList = sysDictDataService.selectDictDataList(sysDictDataParam);
        List<String> levelList = new ArrayList<>();
        sysDictDataList.sort(Comparator.comparing(SysDictData::getDictSort).reversed());
        for (SysDictData sysDictData : sysDictDataList) {
            levelList.add(sysDictData.getDictLabel());
        }
        itemDataList.put("levelList",levelList);

        Date startDate = DateUtils.dateTime("yyyy-MM-dd HH:mm:ss",startTime+" 00:00:00");
        Date endDate = DateUtils.dateTime("yyyy-MM-dd HH:mm:ss",endTime + " 23:59:59");

        BusWaterAutomonitorevaluateDaydata busWaterAutomonitorevaluateHourdataParam = new BusWaterAutomonitorevaluateDaydata();
        busWaterAutomonitorevaluateHourdataParam.setSegmentid(id);
        busWaterAutomonitorevaluateHourdataParam.setStartTime(startDate);
        busWaterAutomonitorevaluateHourdataParam.setEndTime(endDate);
        List<BusWaterAutomonitorevaluateDaydata> statisList = busWaterAutomonitorevaluateDaydataMapper.selectBusWaterAutomonitorevaluateDaydataList(busWaterAutomonitorevaluateHourdataParam);

        while(!startDate.after(endDate)){
            String dayTime = DateUtils.parseDateToStr("yyyy-MM-dd",startDate);
            if(itemDataList.containsKey("dateList")){
                List<String> dateList = itemDataList.get("dateList");
                dateList.add(dayTime);
                itemDataList.put("dateList",dateList);
            }else{
                List<String> dateList = new ArrayList<>();
                dateList.add(dayTime);
                itemDataList.put("dateList",dateList);
            }
            String itemName = "level";

            Map itemDataMap = new HashMap();
            itemDataMap.put("dataTime",dayTime);
            itemDataMap.put("item",itemName);
            String level = "无类别";

            for (BusWaterAutomonitorevaluateDaydata statisMap : statisList) {
                String statisDay = DateUtils.parseDateToStr("yyyy-MM-dd",statisMap.getSampletime());
                if(statisDay.equals(dayTime)){
                    if(StringUtils.isNotEmpty(statisMap.getQualitylevelname())){
                        level = statisMap.getQualitylevelname();
                    }
                    break;
                }
            }
            if(itemDataList.containsKey(itemName)){
                List<String> dataList = itemDataList.get(itemName);
                dataList.add(level);
                itemDataList.put(itemName,dataList);
            }else{
                List<String> dataList = new ArrayList<>();
                dataList.add(level);
                itemDataList.put(itemName,dataList);
            }
            startDate = DateUtils.addDays(startDate,1);
        }
        return itemDataList;
    }

    @Override
    public Map autoQualityCalendar(String year, String segmentId, String isOverStandard) {
        Map resMap = new HashMap();

        Date startDate = DateUtils.dateTime("yyyy-MM-dd HH:mm:ss",year+"-01-01 00:00:00");
        Date endDate = DateUtils.dateTime("yyyy-MM-dd HH:mm:ss",year+"-12-31 23:59:59");
        BusWaterAutomonitorevaluateDaydata param = new BusWaterAutomonitorevaluateDaydata();
        param.setStartTime(startDate);
        param.setEndTime(endDate);
        param.setSegmentid(segmentId);
        if(StringUtils.isNotEmpty(isOverStandard)){
            param.setIsoverstandard(isOverStandard);
        }
        int excellentThreeDays = 0;
        String excellentThreeProportion = "0%";
        int standardDays = 0;
        String standardProportion  = "0%";
        int allDays = 0;

        List<BusWaterAutomonitorevaluateDaydata> daydataList = selectBusWaterAutomonitorevaluateDaydataList(param);
        if(!CollectionUtils.isEmpty(daydataList)){
            allDays = daydataList.size();
            for (BusWaterAutomonitorevaluateDaydata daydata : daydataList) {
                if("1".equals(daydata.getQualitylevel()) ||"2".equals(daydata.getQualitylevel()) || "3".equals(daydata.getQualitylevel())){
                    excellentThreeDays++;
                }
                if("0".equals(daydata.getIsoverstandard())){
                    standardDays++;
                }
            }
        }
        if(allDays>0){
            excellentThreeProportion = String.format("%.1f",((float)excellentThreeDays/(float)allDays)*100f)+"%";
            standardProportion  = String.format("%.1f",((float)standardDays/(float)allDays)*100f)+"%";
        }

        resMap.put("excellentDays",excellentThreeDays);
        resMap.put("excellentProportion",excellentThreeProportion);
        resMap.put("standardDays",standardDays);
        resMap.put("standardProportion",standardProportion);

        Map<String,List<Map>> monthMap = new LinkedHashMap();
        while(startDate.before(endDate)){
            String month = DateUtils.parseDateToStr("yyyy-MM",startDate);
            String day = DateUtils.parseDateToStr("yyyy-MM-dd",startDate);
            String qualityLevelName = "";
            String qualityLevel = "";
            String overStandard = "";
            if(!CollectionUtils.isEmpty(daydataList)){
                for (BusWaterAutomonitorevaluateDaydata daydata : daydataList) {
                    String dataDay = DateUtils.parseDateToStr("yyyy-MM-dd",daydata.getSampletime());
                    if(dataDay.equals(day)){
                        qualityLevelName = daydata.getQualitylevelname();
                        qualityLevel = daydata.getQualitylevel();
                        overStandard = daydata.getIsoverstandard();
                        break;
                    }
                }
            }
            Map dataMap = new HashMap();
            dataMap.put("day",day);
            dataMap.put("qualityLevelName",qualityLevelName);
            dataMap.put("qualityLevel",qualityLevel);
            if("0".equals(overStandard)){
                dataMap.put("standard","1");
            }else{
                dataMap.put("standard","0");
            }
            if(monthMap.containsKey(month)){
                List<Map> dataList = monthMap.get(month);
                dataList.add(dataMap);
                monthMap.put(month,dataList);
            }else{
                List<Map> dataList = new ArrayList<>();
                dataList.add(dataMap);
                monthMap.put(month,dataList);
            }
            startDate = DateUtils.addDays(startDate,1);
        }

        List<Map> monthDataList = new ArrayList<>();

        Set<String> keySet = monthMap.keySet();
        for (String key : keySet) {
            Map monthData = new HashMap();
            monthData.put("month",key);
            int standardCount = 0;
            List<Map> mapList = monthMap.get(key);
            for (Map map : mapList) {
                if("1".equals(map.get("standard"))){
                    standardCount++;
                }
            }
            monthData.put("standardDays",standardCount);
            monthData.put("standardProportion",String.format("%.1f",((float)standardCount/(float)mapList.size())*100f)+"%");
            monthData.put("dayDataList",mapList);
            monthDataList.add(monthData);
        }
        resMap.put("monthDataList",monthDataList);
        return resMap;
    }

    @Override
    public List<Map<String, Object>> getWaterAutoEvaluateDayList(Map<String, Object> params) {
        List<Map<String, Object>> resultList=new ArrayList<>();
        if (StringUtils.isEmpty(params.get("beginTime")!=null  ? params.get("beginTime").toString() : "") || StringUtils.isEmpty(params.get("endTime")!=null ? params.get("endTime").toString() : "")){
            params.put("beginTime", DateUtils.parseDateToStr("yyyy-MM-dd",DateUtils.addDay(DateUtils.getNowDate(),-1)));
            params.put("endTime", DateUtils.parseDateToStr("yyyy-MM-dd",DateUtils.addDay(DateUtils.getNowDate(),-1)));
        }else {
            params.put("beginTime", DateUtils.parseDateToStr("yyyy-MM-dd",DateUtils.parseDate(params.get("beginTime").toString())));
            params.put("endTime", DateUtils.parseDateToStr("yyyy-MM-dd",DateUtils.parseDate(params.get("endTime").toString())));
        }
        resultList = busWaterAutomonitorevaluateDaydataMapper.getWaterAutoEvaluateDayList(params);
        // 假如查询为空，再往前推一天查询
        if (StringUtils.isEmpty(resultList)){
            params.put("beginTime", DateUtils.parseDateToStr("yyyy-MM-dd",DateUtils.addDay(DateUtils.getNowDate(),-2)));
            params.put("endTime", DateUtils.parseDateToStr("yyyy-MM-dd",DateUtils.addDay(DateUtils.getNowDate(),-2)));
            resultList = busWaterAutomonitorevaluateDaydataMapper.getWaterAutoEvaluateDayList(params);
        }
        return resultList;
    }

    @Override
    public Map trendStatis(String id, String startTime, String endTime,String items) {
        List<String> queryItemList = new ArrayList<>();
        if(StringUtils.isNotEmpty(items)){
            queryItemList = Arrays.asList(items.split(","));
        }

        Map<String,List<String>> itemDataList = new HashMap<>();
        BussinessItemVo vo = new BussinessItemVo();
        vo.setBussinessCategoryCode("Auto");
        List<Map<String,Object>> itemList=publicToolsService.bussinessItemData(vo);
        Date startDate = DateUtils.dateTime("yyyy-MM-dd HH:mm:ss",startTime+" 00:00:00");
        Date endDate = DateUtils.dateTime("yyyy-MM-dd HH:mm:ss",endTime+" 23:59:59");

        List<Map> statisList = busWaterAutomonitorevaluateDaydataMapper.trendStatis(id,startDate,endDate);

        while(!startDate.after(endDate)){
            String dayTime = DateUtils.parseDateToStr("yyyy-MM-dd",startDate);
            if(itemDataList.containsKey("dateList")){
                List<String> dateList = itemDataList.get("dateList");
                dateList.add(dayTime);
                itemDataList.put("dateList",dateList);
            }else{
                List<String> dateList = new ArrayList<>();
                dateList.add(dayTime);
                itemDataList.put("dateList",dateList);
            }
            for (Map<String, Object> itemMap : itemList) {
                String itemName = StringUtils.getString(itemMap.get("itemName"));
                if(!queryItemList.contains(itemName)){
                    continue;
                }
                Map itemDataMap = new HashMap();
                itemDataMap.put("dataTime",dayTime);
                itemDataMap.put("item",itemName);
                String effectiveValue = "0";

                for (Map statisMap : statisList) {
                    String statisDay = StringUtils.getString(statisMap.get("dataDay"));
                    String statisItem = StringUtils.getString(statisMap.get("itemName"));
                    String effective = StringUtils.getString(statisMap.get("effectiveValue"));
                    if(statisDay.equals(dayTime) && itemName.equals(statisItem)){
                        if(StringUtils.isNotEmpty(effective)){
                            effectiveValue = effective;
                        }
                        break;
                    }
                }
                if(itemDataList.containsKey(itemName)){
                    List<String> dataList = itemDataList.get(itemName);
                    dataList.add(effectiveValue);
                    itemDataList.put(itemName,dataList);
                }else{
                    List<String> dataList = new ArrayList<>();
                    dataList.add(effectiveValue);
                    itemDataList.put(itemName,dataList);
                }
            }
            startDate = DateUtils.addDays(startDate,1);
        }
        return itemDataList;
    }
}
